<template>
  <div class="page-container">
    <div class="page-header">
      <h2>业务管理</h2>
      <p>管理系统中的所有业务项目</p>
    </div>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="业务名称">
          <el-input 
            v-model="searchForm.businessName" 
            placeholder="请输入业务名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户">
          <el-select 
            v-model="searchForm.customerId" 
            placeholder="请选择客户"
            clearable
            filterable
          >
            <el-option 
              v-for="item in customerOptions" 
              :key="item.id" 
              :label="item.companyName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select 
            v-model="searchForm.businessTypeId" 
            placeholder="请选择业务类型"
            clearable
            style="width: 150px"
          >
            <el-option 
              v-for="item in typeOptions" 
              :key="item.id" 
              :label="item.typeName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.businessStatus" 
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新增业务
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" stripe border>
      <el-table-column prop="businessCode" label="业务编号" width="120" />
      <el-table-column prop="businessName" label="业务名称" min-width="150" />
      <el-table-column prop="customerName" label="客户" width="150" />
      <el-table-column prop="businessTypeName" label="业务类型" width="120" />
      <el-table-column prop="responsibleEmployeeName" label="负责人" width="100" />
      <el-table-column prop="businessStatus" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.businessStatus)">{{ row.businessStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="businessAmount" label="金额" width="120">
        <template #default="{ row }">
          ¥{{ formatMoney(row.businessAmount) }}
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="{ row }">
          <span :class="`priority-tag ${getPriorityClass(row.priority)}`">{{ row.priority }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开始日期" width="120" />
      <el-table-column prop="endDate" label="结束日期" width="120" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogMode === 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务编号" prop="businessCode">
              <el-input v-model="formData.businessCode" placeholder="请输入业务编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务名称" prop="businessName">
              <el-input v-model="formData.businessName" placeholder="请输入业务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="formData.customerId" placeholder="请选择客户" filterable>
                <el-option 
                  v-for="item in customerOptions" 
                  :key="item.id" 
                  :label="item.companyName" 
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessTypeId">
              <el-select v-model="formData.businessTypeId" placeholder="请选择业务类型">
                <el-option 
                  v-for="item in typeOptions" 
                  :key="item.id" 
                  :label="item.typeName" 
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsibleEmployeeId">
              <el-select v-model="formData.responsibleEmployeeId" placeholder="请选择负责人">
                <el-option 
                  v-for="item in employeeOptions" 
                  :key="item.id" 
                  :label="item.realName" 
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务状态" prop="businessStatus">
              <el-select v-model="formData.businessStatus" placeholder="请选择状态">
                <el-option label="待处理" value="待处理" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已取消" value="已取消" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务金额" prop="businessAmount">
              <el-input-number 
                v-model="formData.businessAmount" 
                :min="0" 
                :precision="2"
                :step="1000"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择优先级">
                <el-option label="低" value="低" />
                <el-option label="中" value="中" />
                <el-option label="高" value="高" />
                <el-option label="紧急" value="紧急" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker 
                v-model="formData.startDate" 
                type="date" 
                placeholder="请选择开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker 
                v-model="formData.endDate" 
                type="date" 
                placeholder="请选择结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务描述" prop="description">
              <el-input 
                v-model="formData.description" 
                type="textarea" 
                :rows="3"
                placeholder="请输入业务描述" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogMode !== 'create'">
            <el-form-item label="进度备注" prop="progressNotes">
              <el-input 
                v-model="formData.progressNotes" 
                type="textarea" 
                :rows="3"
                placeholder="请输入进度备注" 
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div v-if="dialogMode === 'view'">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
        <div v-else>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  getBusinesses, 
  getBusiness,
  createBusiness, 
  updateBusiness, 
  deleteBusiness,
  updateBusinessStatus,
  updateBusinessProgress
} from '@/api/businesses'
import { getActiveBusinessTypes } from '@/api/businessTypes'
import { getCustomers } from '@/api/customers'
import { getEmployees } from '@/api/employees'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const submitLoading = ref(false)
const customerOptions = ref([])
const typeOptions = ref([])
const employeeOptions = ref([])

// 搜索表单
const searchForm = reactive({
  businessName: '',
  customerId: '',
  businessTypeId: '',
  businessStatus: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('create') // create, edit, view
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  businessCode: '',
  businessName: '',
  customerId: '',
  businessTypeId: '',
  responsibleEmployeeId: '',
  businessStatus: '待处理',
  businessAmount: 0,
  startDate: '',
  endDate: '',
  priority: '中',
  description: '',
  progressNotes: ''
})

// 表单验证规则
const formRules = {
  businessCode: [
    { required: true, message: '请输入业务编号', trigger: 'blur' }
  ],
  businessName: [
    { required: true, message: '请输入业务名称', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  businessTypeId: [
    { required: true, message: '请选择业务类型', trigger: 'change' }
  ],
  responsibleEmployeeId: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    create: '新增业务',
    edit: '编辑业务',
    view: '查看业务'
  }
  return titles[dialogMode.value]
})

// 格式化金额
const formatMoney = (amount) => {
  return new Intl.NumberFormat('zh-CN').format(amount)
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '进行中': 'primary',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    '低': 'low',
    '中': 'medium', 
    '高': 'high',
    '紧急': 'urgent'
  }
  return priorityMap[priority] || 'medium'
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response = await getBusinesses(params)
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        tableData.value = responseData.data
        pagination.total = responseData.total || 0
        console.log('成功加载业务数据:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        tableData.value = responseData
        pagination.total = responseData.length
      } else {
        console.warn('API返回的数据格式不正确:', responseData)
        tableData.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取业务列表失败:', error)
    ElMessage.error('获取业务列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取客户选项
const getCustomerOptions = async () => {
  try {
    const response = await getCustomers({ pageSize: 1000 })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        customerOptions.value = responseData.data
      } else if (responseData && Array.isArray(responseData)) {
        customerOptions.value = responseData
      } else {
        customerOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取客户选项失败:', error)
    ElMessage.error('获取客户选项失败')
  }
}

// 获取业务类型选项
const getTypeOptions = async () => {
  try {
    const response = await getActiveBusinessTypes()
    if (response.code === 200) {
      typeOptions.value = response.data || []
    }
  } catch (error) {
    console.error('获取业务类型选项失败:', error)
    ElMessage.error('获取业务类型选项失败')
  }
}

// 获取员工选项
const getEmployeeOptions = async () => {
  try {
    const response = await getEmployees({ pageSize: 1000 })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        employeeOptions.value = responseData.data
      } else if (responseData && Array.isArray(responseData)) {
        employeeOptions.value = responseData
      } else {
        employeeOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取员工选项失败:', error)
    ElMessage.error('获取员工选项失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    businessName: '',
    customerId: '',
    businessTypeId: '',
    businessStatus: ''
  })
  handleSearch()
}

// 新增
const handleCreate = () => {
  dialogMode.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogMode.value = 'edit'
  resetFormData()
  try {
    const response = await getBusiness(row.id)
    if (response.code === 200) {
      Object.assign(formData, response.data)
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取业务详情失败:', error)
    ElMessage.error('获取业务详情失败')
  }
}

// 查看
const handleView = (row) => {
  router.push(`/dashboard/businesses/detail/${row.id}`)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除业务"${row.businessName}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    await deleteBusiness(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  getTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.page = val
  getTableData()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogMode.value === 'create') {
      await createBusiness(formData)
      ElMessage.success('新增成功')
    } else {
      await updateBusiness(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 弹窗关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
  dialogVisible.value = false
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    businessCode: '',
    businessName: '',
    customerId: '',
    businessTypeId: '',
    responsibleEmployeeId: '',
    businessStatus: '待处理',
    businessAmount: 0,
    startDate: '',
    endDate: '',
    priority: '中',
    description: '',
    progressNotes: ''
  })
}

// 页面初始化
onMounted(() => {
  getTableData()
  getCustomerOptions()
  getTypeOptions()
  getEmployeeOptions()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}
</style> 